<template>
  <div class="container bg-white">
    <div>您已经成功领取奖励，注册完成即可使用</div>
    <van-cell-group>
      <van-field
        ref="mobile"
        v-model="formData.mobile"
        required
        clearable
        label="手机号"
        :error-message="errorMsg.mobile"
      />
      <van-field
        ref="code"
        v-model="formData.code"
        center
        required
        clearable
        label="验证码"
        placeholder="请输入验证码"
        :error-message="errorMsg.code"
      >
        <van-button
          slot="button"
          size="small"
          :disabled="countdown > 0"
          @click="sendMobileCode"
          type="primary"
        >{{ countdown ? countdown + 's' : '发送验证码'}}</van-button>
      </van-field>
      <van-field
        ref="password"
        v-model="formData.password"
        required
        clearable
        type="password"
        label="密码"
        placeholder="请输入密码"
        :error-message="errorMsg.password"
      />
    </van-cell-group>

    <div class="mtype-action">
      <van-button
        size="large"
        block
        @click="onSubmit"
        :disabled="disableSubmit"
      >立即注册</van-button>
    </div>
  </div>
</template>

<script>
import validator from '../../common/validator'
import {
  Row,
  Col,
  Cell,
  Button,
  CellGroup,
  Field,
  Area,
  Icon,
  Image,
  Popup,
  Picker,
  Lazyload
} from 'vant'

export default {
  components: {
    [Row.name]: Row,
    [Col.name]: Col,
    [Cell.name]: Cell,
    [Button.name]: Button,
    [CellGroup.name]: CellGroup,
    [Field.name]: Field,
    [Area.name]: Area,
    [Icon.name]: Icon,
    [Popup.name]: Popup,
    [Image.name]: Image,
    [Picker.name]: Picker,
    Lazyload
  },

  data () {
    return {
      countdown: 0,
      apply: {
        memberId: 0,
        mobile: '',
        password: '',
        code: ''
      },

      disableSubmit: false,

      errorMsg: {
        password: '',
        mobile: '',
        code: ''
      },
      rules: {
        mobile: [
          {
            validator: (rule, value, callBack) => {
              if (!value) {
                callBack('请输入手机号码')
              } else if (/^[1][3-9][0-9]{9}$/.test(value)) {
                callBack()
              } else {
                callBack('请输入正确的手机号码')
              }
            }
          }
        ],
        password: [{ required: true, message: '请设置登录密码' }],
        code: [{ required: true, message: '请输入验证码' }]
      }
    }
  },

  created () {
    console.log(this.$store.state.spread)
    this.apply.mobile = this.receiveMobile
  },
  watch: {
    formData: {
      handler (cv, ov) {
        cv['mobile'] = this.receiveMobile
        this.validator = validator(this.rules, cv)
      },
      deep: true
    }
  },
  computed: {
    formData () {
      return this.apply
    },
    receiveMobile () {
      return this.$store.state.spread.receiveMobile
    }
  },

  methods: {
    onSubmit () {
      console.log(this.formData)
      this.validate((errors, fields) => {
        if (errors) {
          if (fields.length > 0) {
            let first = fields.shift()
            console.log(first)
            this.$refs[first.field].focus()
          }
          console.log(this.errorMsg)
        } else {
          this.submit()
        }
        console.log(fields)
      })
    },
    submit () {
      this.disableSubmit = true
      this.axios
        .post('/spread/register', {
          params: this.apply,
          headers: { openAuth: true, FastMode: true }
        })
        .then(response => {
          if (response.data) {
            this.$router.replace({ name: 'spread/success' })
          } else {
            this.$toast('提交失败~')
            this.disableSubmit = false
          }
        })
        .catch(error => {
          this.disableSubmit = false
          this.$toast(error)
        })
    },
    sendsms () {
      this.axios
        .post('/sms/captcha', {
          mobile: this.apply.mobile,
          scope: 'register'
        })
        .then(response => {
          if (response.data) {
            this.$toast('发送成功')
            this.countdown = 60
            this.countdownSubtract()
          } else {
            this.$toast('发送失败')
          }
        })
        .catch(error => {
          console.log(error.data)
          this.$toast(error.data.message)
        })
    },
    sendMobileCode () {
      this.validate(errors => {
        if (!errors) {
          this.sendsms()
        }
      }, 'mobile')
    },
    countdownSubtract () {
      if (this.countdown > 0) {
        setTimeout(() => {
          this.countdown -= 1
          this.countdownSubtract()
        }, 1000)
      }
    },
    /**
     * 清除验证提示
     * @param attrs
     */
    resetField (attrs) {
      attrs = !attrs
        ? Object.keys(this.errorMsg)
        : Array.isArray(attrs)
          ? attrs
          : [attrs]
      attrs.forEach(attr => {
        this.errorMsg[attr] = ''
      })
    },
    /**
     * 验证方法
     * @param callback
     * @param data
     */
    validate (callback, data) {
      this.validator.validate((errors, fields) => {
        this.resetField()
        if (errors) {
          fields.forEach(item => {
            this.errorMsg[item.field] = item.message
          })
        }
        callback && callback(errors, fields)
      }, data)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.sigin-dashboard {
}
</style>
